<?php
/**有道翻译例子**/

require_once 'faceshibie/facepp_sdk.php';
//translate($keyword);
traceHttp();
define("TOKEN", "weixin");
define("DEBUG", "debug");
ini_set('display_errors',1);
//ob_start(logger);

           
$wechatObj = new wechatCallbackapiTest();

//$wechatObj->responseMsg();

if (!isset($_GET['echostr'])) {
    $wechatObj->responseMsg();
}else{
    $wechatObj->valid();
}

class wechatCallbackapiTest
{
    
    
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        
        if($this->checkSignature()){
            header('content-type:text');
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    
    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE)
            {
                case "text":
                    $resultStr = $this->receiveText($postObj);
                    break;
                case "event":
                    $resultStr = $this->receiveEvent($postObj);
                    break;
                case "image":
                	$resultStr = $this->receiveImg($postObj);
                    break;
                case "voice":
                	$resultStr = $this->receiveVoice($postObj);
                    break;
                default:
                    $resultStr = "unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }

    

    private function receiveText($object)
    {
        $funcFlag = 0;
        $keyword = trim($object->Content);
        $resultStr = "";
        $cityArray = array();
        $contentStr = "";
        $needArray = false;
        $illegal = false;
        $saytome = false;
        
        
        sae_debug("subsbu  ".substr($keyword,0,6)."\n"); 

        if (strlen($keyword) >= 6 && (substr($keyword,0,6) == "翻译" || substr($keyword,0,6) == "翻譯") ){
            $contentStr = translate(substr($keyword,6,strlen($keyword)-6));
            $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
            
            return $resultStr;
        }
        else
            return $this->transmitText($object, "欢迎关注滚十测试号，1、翻译+内容 中英翻译\n2、发送头像进行人脸分析\n3、发送国语实时翻译", $funcFlag);
    }
    
    private function receiveImg($object)
    {
        $funcFlag = 0;
        $picUrl = $object->PicUrl;
        $msgID = $object->MsgId;
        $mediaID = $object->MediaId;

        
        $facepp = new Facepp(); 
        //$params=array('url'=>'http://www.faceplusplus.com.cn/wp-content/themes/faceplusplus/assets/img/demo/2.jpg');
        $params=array('url'=> "{$picUrl}");
        $params['attribute'] = 'gender,age,race,smiling,glass,pose';
        $response = $facepp->execute('/detection/detect',$params);

		sae_debug("脸部URL ".$picUrl);
            
        if($response['http_code']==200){
            #json decode 
            $data = json_decode($response['body'],1);
            #get face landmark
            foreach ($data['face'] as $face) {
        		$attr = $face['attribute'];
                if(!empty($attr['glass']))
                    $glass = $attr['glass']['value'];
                if(!empty($attr['pose']))
                    $pose = ',抬头角度'.$attr['pose']['pitch_angle']['value'].'旋转度'.$attr['pose']['roll_angle']['value'].'摇头度'.$attr['pose']['yaw_angle']['value'];
                $back .='年龄:'.$attr['age']['value'].'±'.$attr['age']['range'].',性别:'. $attr['gender']['value'].',种族:'.$attr['race']['value'].',微笑度:'.$attr['smiling']['value'].'眼镜佩戴分析:'.$glass.$pose."\n";
                //sae_debug($back);
                //logger($back);
            }
            
        }
        else
        {
            $back ="图片识别异常".$response['http_code'] ;
            sae_debug($back );
        }
        return $this->transmitText($object, $back, $funcFlag);        
    }
    
    private function receiveVoice($object)
    {  
        $mediaID = $object->MediaId;
        $format = $object->Format;
        if (isset($object->Recognition) && !empty($object->Recognition))
        {
            $recognition = $object->Recognition; //语音识别后内容
            //sae_debug($recognition);
    	}else
        {
            $recognition = "未开启语音识别功能或者识别内容为空";
           	sae_debug("不存在语音识别");
        }
        $msgID = $object->MsgId;
      
        return $this->transmitText($object, $recognition);
    }
    
    
    private function receiveEvent($object)
    {
        $contentStr = "";
        switch ($object->Event)
        {
            case "subscribe":
            	$contentStr = "欢迎关注滚十测试号，1、翻译+内容 中英翻译\n2、发送头像进行人脸分析\n3、发送国语实时翻译";
                break;
            case "unsubscribe":
                $contentStr = "";
                break;
            case "CLICK":
                switch ($object->EventKey)
                {
                    default:
                        $contentStr = "receive a eventkey: ".$object->EventKey;
                        break;
                }
                break;
            default:
                $contentStr = "receive a new event: ".$object->Event;
                break;
        }
        $resultStr = $this->transmitText($object, $contentStr);
        return $resultStr;
    }
   
    private function transmitText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }
    
    
    
    
}

	function translate($keyword)
    {
        $url="http://fanyi.youdao.com/openapi.do?keyfrom=twoplus&key=910931482&type=data&doctype=json&version=1.2&q=".urlencode($keyword);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        
        $youdaoResult = json_decode($output, true);
        $errorcode = $youdaoResult['errorCode']; 
        $ex = $youdaoResult['basic']['explains'];       
  
        
        if(!empty($ex))
        {
            foreach( $ex as   $v){
                $result .= "\n".$v;
            }
        }
        else
            sae_debug('EMPTY#####');
            
        if(isset($errorcode) && $errcode ==0 ){
            return $youdaoResult['translation'][0]."\n音标:[".$youdaoResult['basic']['phonetic']."]".$result;
        }
        else
        {
            return '翻译失败，错误码: '.$errorcode;
        }
    }

	function traceHttp()
    {
        logger("\n\nREMOTE_ADDR:".$_SERVER["REMOTE_ADDR"].(strstr($_SERVER["REMOTE_ADDR"],'101.226')? " FROM WeiXin": "Unknown IP"));
        logger("QUERY_STRING:".$_SERVER["QUERY_STRING"]);
    }
    
    function logger($log_content)
    {
                //var_dump(gettype($ex));
        //print_r($youdaoResult);  
        /*
        if(!isset( $GLOBALS['DEBUG'] ) ){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else */
        { //LOCAL
            $max_size = 500000;
            $log_filename = "saestor://firstbucket//errlog.txt";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n");
        }
    }

?>